import { useRaf } from '@/components';
import { defaultShouldUpdate } from '@/utils';
import { useState } from 'react';

function useRefState(ref, getState = (v) => v, shouldUpdate = defaultShouldUpdate) {
  const [state, setState] = useState(getState(ref.current));

  useRaf(() => {
    const curr = getState(ref.current);
    if (shouldUpdate(state, curr)) setState(curr);
  });

  return state;
}

export default useRefState;
